from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import PermissionDenied
from django.contrib import messages
from django.shortcuts import redirect
from .utils import is_admin, is_college_user


class AdminRequiredMixin(LoginRequiredMixin):
    """管理员权限混入类"""
    
    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return self.handle_no_permission()
        
        if not is_admin(request.user):
            messages.error(request, '您没有权限访问此页面')
            return redirect('dashboard')
        
        return super().dispatch(request, *args, **kwargs)


class CollegeUserRequiredMixin(LoginRequiredMixin):
    """二级学院用户权限混入类"""
    
    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return self.handle_no_permission()
        
        if not (is_admin(request.user) or is_college_user(request.user)):
            messages.error(request, '您没有权限访问此页面')
            return redirect('dashboard')
        
        return super().dispatch(request, *args, **kwargs)


class RoleRequiredMixin(LoginRequiredMixin):
    """角色权限混入类"""
    allowed_roles = []
    
    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return self.handle_no_permission()
        
        try:
            user_role = request.user.userprofile.role
            if user_role not in self.allowed_roles:
                messages.error(request, '您没有权限访问此页面')
                return redirect('dashboard')
        except AttributeError:
            messages.error(request, '用户信息不完整，请联系管理员')
            return redirect('dashboard')
        
        return super().dispatch(request, *args, **kwargs)


class OwnerRequiredMixin(LoginRequiredMixin):
    """所有者权限混入类"""
    
    def get_object(self, queryset=None):
        obj = super().get_object(queryset)
        
        # 管理员可以访问所有对象
        if is_admin(self.request.user):
            return obj
        
        # 检查是否为对象的创建者
        if hasattr(obj, 'created_by') and obj.created_by == self.request.user:
            return obj
        
        # 权限不足
        messages.error(self.request, '您没有权限访问此对象')
        raise PermissionDenied('您没有权限访问此对象')